package cn.stronglink.asset.module.assetmanage.instock.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.toolkit.IdWorker;

import cn.stronglink.asset.model.AssetBrand;
import cn.stronglink.asset.model.AssetModel;
import cn.stronglink.asset.model.AssetType;
import cn.stronglink.asset.model.Preset;
import cn.stronglink.asset.model.PresetDetail;
import cn.stronglink.asset.module.assetmanage.instock.service.PresetDetailService;
import cn.stronglink.asset.module.assetmanage.instock.service.PresetService;
import cn.stronglink.asset.module.basicdata.assetBrand.service.AssetBrandService;
import cn.stronglink.asset.module.basicdata.assetModel.service.AssetModelService;
import cn.stronglink.asset.module.basicdata.assetType.service.AssetTypeService;
import cn.stronglink.suite.core.base.AbstractController;
import cn.stronglink.suite.core.exception.BusinessException;
import cn.stronglink.suite.core.log.annotation.OperateLog;
import cn.stronglink.suite.core.log.annotation.OperateLog.OpType;
import cn.stronglink.suite.core.support.HttpCode;
import cn.stronglink.suite.core.util.BmUtils;
import cn.stronglink.suite.core.util.SystemConfigurer;
import cn.stronglink.suite.core.util.WebUtil;

@Controller
@RequestMapping(value = "instock/preset")
public class PresetController extends AbstractController {

	@Autowired
	private PresetService presetService;
	@Autowired
	private PresetDetailService presetDetailService;
	@Autowired
	private AssetTypeService assetTypeService;
	@Autowired
	private AssetModelService assetModelService;
	@Autowired
	private AssetBrandService assetBrandService;
	

	@RequestMapping(value = "queryPresetList")
	public ResponseEntity<ModelMap> queryList(ModelMap modelMap, HttpServletRequest request,
			HttpServletResponse response, @RequestBody Map<String, Object> params) {	
		boolean isAdmin = (boolean) request.getSession().getAttribute("isAdmin");
		if(!isAdmin) {
			params.put("createBy", WebUtil.getCurrentUser());
		}
		@SuppressWarnings("unchecked")
		Page<Preset> page = (Page<Preset>) super.getPage(params);
		Page<Preset> data = presetService.queryList(page,params);
		return setSuccessModelMap(modelMap, data);
	}
	
	@RequestMapping(value = "qryById")
	public ResponseEntity<ModelMap> qryById(ModelMap modelMap, HttpServletRequest request,
			HttpServletResponse response, @RequestBody Long id) {		
		Preset data = presetService.qryById(id);
		return setSuccessModelMap(modelMap, data);
	}
	/**
	 * 创建预置单
	 * @param modelMap
	 * @param request
	 * @param response
	 * @param preset
	 * @return
	 */
	@OperateLog(module = "预置单管理",desc="创建预置单", type = OpType.ADD)
	@RequestMapping(value = "create")
	public ResponseEntity<ModelMap> create(ModelMap modelMap, HttpServletRequest request,
			HttpServletResponse response,@RequestBody Preset preset) {
		presetService.insertPreset(preset);
		return setSuccessModelMap(modelMap, null);
	}
	
	/**
	 * 编辑预置单详情
	 * @param modelMap
	 * @param request
	 * @param response
	 * @param preset
	 * @return
	 */
	@OperateLog(module = "预置单管理",desc="编辑预置单", type = OpType.UPDATE)
	@RequestMapping(value = "edit")
	public ResponseEntity<ModelMap> edit(ModelMap modelMap, HttpServletRequest request,
			HttpServletResponse response,@RequestBody Preset preset) {
		presetService.insertPreset(preset);
		return setSuccessModelMap(modelMap, null);
	}
	
	/**
	 * 删除预置单
	 * @param modelMap
	 * @param request
	 * @param response
	 * @param id
	 * @return
	 */
	@OperateLog(module = "预置单管理",desc="删除预置单", type = OpType.DEL)
	@RequestMapping(value = "remove")
	public ResponseEntity<ModelMap> remove(ModelMap modelMap, HttpServletRequest request,
			HttpServletResponse response,@RequestBody Long id) {
		presetService.removePreset(id);
		return setSuccessModelMap(modelMap, null);
	}

	
	@RequestMapping(value = "queryDetailList")
	public ResponseEntity<ModelMap> queryDetailList(ModelMap modelMap, HttpServletRequest request,
			HttpServletResponse response, @RequestBody Long presetId) {	
		List<PresetDetail> data = presetDetailService.queryDetailList(presetId);
		Preset obj = presetService.qryById(presetId);
		modelMap.put("obj", obj);
		return setSuccessModelMap(modelMap, data);
	}
	
	@RequestMapping(value = "qryDetailById")
	public ResponseEntity<ModelMap> qryDetailInfoById(ModelMap modelMap, HttpServletRequest request,
			HttpServletResponse response, @RequestBody Long id) {		
		PresetDetail data = presetDetailService.qryDetailById(id);
		return setSuccessModelMap(modelMap, data);
	}
	
	@RequestMapping(value = "qryDetailInfoById")
	public ResponseEntity<ModelMap> qryDetailInfoById(ModelMap modelMap, HttpServletRequest request,
			HttpServletResponse response, @RequestBody Map<String, Object> params) {		
		PresetDetail data = presetDetailService.qryDetailById(Long.parseLong(params.get("id").toString()));
		return setSuccessModelMap(modelMap, data);
	}
	
	/**
	 * 添加预置单详情
	 * @param modelMap
	 * @param request
	 * @param response
	 * @param presetDetail
	 * @return
	 */
	@OperateLog(module = "预置单管理",desc="添加预置单详情", type = OpType.ADD)
	@RequestMapping(value = "createDetail")
	public ResponseEntity<ModelMap> createDetail(ModelMap modelMap, HttpServletRequest request,
			HttpServletResponse response,@RequestBody PresetDetail presetDetail) {
		if (presetDetail.getAssetNo()!=null&&!"".equals(presetDetail.getAssetNo())) {
			Integer assetNoNum = presetDetailService.checkAssetNoNum(presetDetail.getAssetNo(),null);
			if (assetNoNum.equals(0)) {
				presetDetailService.insertPresetDetail(presetDetail);
				return setSuccessModelMap(modelMap, null);
			}else {
				return setModelMap(modelMap, HttpCode.CONFLICT, "资产编号已经存在");
			}
		}
		presetDetailService.insertPresetDetail(presetDetail);
		return setSuccessModelMap(modelMap, null);
	}
	
	/**
	 * 编辑预置单详情项
	 * @param modelMap
	 * @param request
	 * @param response
	 * @param presetDetail
	 * @return
	 */
	@OperateLog(module = "预置单管理",desc="编辑预置单详情项", type = OpType.UPDATE)
	@RequestMapping(value = "editDetail")
	public ResponseEntity<ModelMap> editDetail(ModelMap modelMap, HttpServletRequest request,
			HttpServletResponse response,@RequestBody PresetDetail presetDetail) {
		if (presetDetail.getAssetNo()!=null&&!"".equals(presetDetail.getAssetNo())) {
			Integer assetNoNum = presetDetailService.checkAssetNoNum(presetDetail.getAssetNo(),presetDetail.getId());
			if (assetNoNum.equals(0)) {
				presetDetailService.insertPresetDetail(presetDetail);
				return setSuccessModelMap(modelMap, null);
			}else {
				return setModelMap(modelMap, HttpCode.CONFLICT, "资产编号已经存在");
			}
		}else {
			return setModelMap(modelMap, HttpCode.CONFLICT, "资产编号不能为空");
		}
	}
	
	
	@OperateLog(module = "预置单管理",desc="删除预置单详情项", type = OpType.DEL)
	@RequestMapping(value = "removeDetail")
	public ResponseEntity<ModelMap> removeDetail(ModelMap modelMap, HttpServletRequest request,
			HttpServletResponse response,@RequestBody Long id) {
		presetDetailService.removePresetDetail(id);
		return setSuccessModelMap(modelMap, null);
	}
	
	public static boolean isRowEmpty(Row row) {
		if (row==null) {
			return true;
		}else {
			for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
			       Cell cell = row.getCell(c);
			       if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK)
			           return false;
			   }
			   return true;
		}
		}
	/**
	 * 导入EXCEL文件
	 * @param file
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "importPreset")
	public ResponseEntity<ModelMap> importPreset(@RequestParam(value = "file", required = true) MultipartFile file,HttpServletRequest request,
			HttpServletResponse response,ModelMap modelMap) throws Exception{
		Long presetId =Long.parseLong(request.getParameter("presetId"));
		List<String> dataList=new ArrayList<String>();
		//导入Excel操作
		//导入Excel文件不为空时，将文件写入流，然后转化为工作薄
		if (file!=null){
			try {	
				Workbook workBook = null;
				String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());
				if(!"xls".equals(fileType)&&!"xlsx".equals(fileType)){
					throw new BusinessException("请选择excel格式文件！");
				}
				int header=0;
				workBook = WorkbookFactory.create(file.getInputStream());
				if (workBook.getNumberOfSheets()>0){
					//获取第一个单元薄
					Sheet sheet = workBook.getSheetAt(0);
					//获取单元薄中表头信息,并将表头中每个单元格中信息存入数组headNames中
					Row rowHead = sheet.getRow(header); 
					if (rowHead != null) {
						String[] headNames = new String[rowHead.getLastCellNum()];
						// 获取该行中总共有多少列数据row.getLastCellNum()
						for (int j = 0; j < rowHead.getLastCellNum(); j++) {
							Cell cell = rowHead.getCell(j);
							if (cell == null) {
								continue;
							} else {
								// 获取表头各个字段名称
								String returnStr = BmUtils.getCellValue(cell);
								headNames[j] = returnStr;
							}
						}
						if (headNames!=null&&headNames.length>0) {
							String allTitle=(String)SystemConfigurer.getContextProperty("presetTitleModel");
							//String allTitle = "资产编号;设备名称;资产分类;品牌;型号;价格;描述;";
							for (String name : headNames) {
								if (allTitle.indexOf(name)==-1) {
									throw new BusinessException("请使用模板文件！");
								}
							}
						}
						List<PresetDetail> presetDetailList = new ArrayList<PresetDetail>();
						List<String> existPreset = presetDetailService.queryAllDetailList();
						List<AssetBrand> brandData = assetBrandService.queryAssetBrandList();//设备品牌列表
						List<AssetModel> modelData = assetModelService.queryListAllS();//设备型号列表
						List<AssetType> typeList = assetTypeService.getListAll();//设备类型列表
						Date date = new Date();
						// 遍历单元簿中每一行，获取每一列字段，并根据表头对应赋值
						int flag=1;
						List<String> currentAssetNo = new ArrayList<String>();
						for (int i = header; i < sheet.getPhysicalNumberOfRows(); i++) {
							Row row = sheet.getRow(i + 1);
							Boolean isRow = isRowEmpty(row);
							PresetDetail detail = null;
							if (!isRow) {
								String rowError="第"+flag+"行   ";
								String data="";
								detail = new PresetDetail();
								int exist=0;
								int assetNoR = 0;
								// 获取该行中总共有多少列数据row.getLastCellNum()
								for (int j = 0; j < row.getLastCellNum(); j++) {
									
									Cell cell = row.getCell(j);
									if (cell == null) {
										continue;
									} else if (StringUtils.hasText(headNames[j])) {
										// 获取单元格内容，并根据单元格类型，进行转化
										String returnStr = BmUtils.getCellValue(cell);
										// 根据给定的Excel格式，进行导入，一下是对应列对应字段
										if (headNames[j].equals("资产编号")) {
											if(returnStr!=null&&!"".equals(returnStr)){
												detail.setAssetNo(returnStr);
												exist=existPreset.contains(returnStr)?1:0;
												if (currentAssetNo!=null&&currentAssetNo.size()>0) {
													assetNoR=currentAssetNo.contains(returnStr)?1:0;
													currentAssetNo.add(returnStr);
												}else {
													currentAssetNo.add(returnStr);
												}
											}
//											else{
//												data += "资产编号不能为空;";
//											}
										} else if (headNames[j].equals("设备名称")) {
											if(returnStr!=null&&!"".equals(returnStr)){
												detail.setAssetName(returnStr);
											}else{
												data += "设备名称不能为空;";
											}
										} else if (headNames[j].equals("价格")) {
											if(returnStr!=null&&!"".equals(returnStr)){
												detail.setPrice(new BigDecimal(returnStr));
											}else{
												data += "价格不能为空;";
											}
										} else if (headNames[j].equals("资产分类")) {
											if(returnStr!=null&&!"".equals(returnStr)){
												if(typeList!=null &&typeList.size()>0){
													boolean isExit=false;
													for(AssetType type : typeList){
														if(type.getName().equals(returnStr)){
															detail.setTypeId(type.getId());
															isExit=true;
															break;
														}
													}
													if(!isExit){
														data += "资产分类不存在，请先添加资产分类.";
													}
												}
											
											}else{
												data += "资产分类不能为空;";
											}
										}else if (headNames[j].equals("品牌")) {											
											if(returnStr!=null&&!returnStr.equals("")){
												if(brandData!=null &&brandData.size()>0){
													boolean isExit=false;
													for(AssetBrand brand : brandData){
														if(brand.getName().equals(returnStr)){
															detail.setBrandId(brand.getId());
															isExit=true;
															break;
														}
													}
													if(!isExit){
														data+="品牌不存在，请先添加品牌;";
													}
												}
												
											}else{
												data +=data==null||"".equals(data)?"品牌不能为空":";品牌不能为空;";
											}
										}else if (headNames[j].equals("型号")) {											
											if(returnStr!=null&&!returnStr.equals("")){
												if(modelData!=null &&modelData.size()>0){
													boolean isExit=false;
													for(AssetModel model : modelData){
														if(model.getName().equals(returnStr)){
															if (detail.getBrandId()!=null&&detail.getTypeId()!=null) {
																if (model.getBrandId().equals(detail.getBrandId())&&model.getTypeId().equals(detail.getTypeId())) {
																	detail.setModelId(model.getId());
																	isExit=true;
																	break;
																}else {
																	data+="型号不属于此数据资产分类或品牌;";
																	isExit=true;
																	break;
																}
															}
														}
													}
													if(!isExit){
														data+="型号不存在，请先添加型号;";
													}
												}
											}else{
												data+="设备型号不能为空;";
											}
										}else if (headNames[j].equals("资产序列号")) {
											detail.setSerialNo(returnStr);
										} else if (headNames[j].equals("描述")) {
											detail.setRemark(returnStr);
										} 
									}

								}
								flag++;
								// 判断当前资产数据是否存在
								if (assetNoR==0&&exist==0&&detail.getAssetNo()!=null&&!"".equals(detail.getAssetNo())) {
									detail.setCreateTime(date);
									detail.setId(IdWorker.getId());
									detail.setPresetId(presetId);
									detail.setStatus(1);
									detail.setCreateBy(WebUtil.getCurrentUser());
									presetDetailList.add(detail);
								}else{
									if (assetNoR==0) {
										data += "资产编号"+detail.getAssetNo()+"已经存在;";
									}else {
										data += "资产编号在导入文件中重复;";
									}
									
								}
								if(data!=null&&!"".equals(data)){
//									if(dataList==null||dataList.size()==0){
//										dataList.add(rowError);
//									}
									dataList.add(rowError);
									dataList.add(data);
								}
							}
						}
						if(dataList!=null&&dataList.size()>0){
							String data="";
							for(String errorData:dataList){
								data+=errorData;
							}
							throw new BusinessException(data);
						}else{
							if(presetDetailList != null && presetDetailList.size() > 0) {
								int num = presetDetailService.createPresetDetailList(presetDetailList);
								if (num == presetDetailList.size()) {
									return setSuccessModelMap(modelMap);
								}
							} else {
								
								return setSuccessModelMap(modelMap);
							}
						}
						
					}
				}
			}catch (IOException e) {
				throw new BusinessException("未知异常!");
			}
		}
		throw new BusinessException("无文件!");
	}
	
}
